const fs = require('fs');
const path = require('path');
const multer = require('multer');
const FormData = require('form-data');
const axios = require('axios');

// 引入数据库模型
require('./db/index'); // 初始化数据库连接
const aiimg = require('./db/aiimg');
const aisave = require('./db/aisave');

// 引入AI分析模块
const faceapi = require('face-api.js');
const { createCanvas, loadImage } = require('canvas');
const { Canvas, Image, ImageData } = require('canvas');
faceapi.env.monkeyPatch({ Canvas, Image, ImageData });

// 配置参数
const TEST_IMAGES_DIR = path.join(__dirname, '../测试图片2');
const UPLOAD_DIR = path.join(__dirname, 'public/uploads');
const API_BASE_URL = 'http://localhost:3000'; // 根据实际端口调整
const BATCH_SIZE = 5; // 批量处理数量，避免同时处理太多图片
const DELAY_BETWEEN_BATCHES = 2000; // 批次间延迟(毫秒)

// 确保上传目录存在
if (!fs.existsSync(UPLOAD_DIR)) {
  fs.mkdirSync(UPLOAD_DIR, { recursive: true });
}

// 日志函数
const log = (message, type = 'info') => {
  const timestamp = new Date().toLocaleString();
  const prefix = {
    info: '📝',
    success: '✅',
    error: '❌',
    warning: '⚠️',
    processing: '🔄'
  }[type] || '📝';
  
  console.log(`[${timestamp}] ${prefix} ${message}`);
};

// 统计信息
const stats = {
  total: 0,
  success: 0,
  failed: 0,
  skipped: 0,
  startTime: null,
  endTime: null
};

// 获取所有图片文件
function getImageFiles() {
  try {
    if (!fs.existsSync(TEST_IMAGES_DIR)) {
      throw new Error(`测试图片目录不存在: ${TEST_IMAGES_DIR}`);
    }

    const files = fs.readdirSync(TEST_IMAGES_DIR);
    const imageFiles = files.filter(file => {
      const ext = path.extname(file).toLowerCase();
      return ['.jpg', '.jpeg', '.png', '.bmp', '.gif'].includes(ext);
    });

    log(`发现 ${imageFiles.length} 个图片文件`);
    return imageFiles;
  } catch (error) {
    log(`获取图片文件失败: ${error.message}`, 'error');
    return [];
  }
}

// 复制图片到上传目录并重命名
function copyImageToUploadDir(imageName) {
  try {
    const sourcePath = path.join(TEST_IMAGES_DIR, imageName);
    
    // 生成唯一文件名
    const ext = path.extname(imageName);
    const uniqueName = `batch-test-${Date.now()}-${Math.round(Math.random() * 1E9)}${ext}`;
    const destPath = path.join(UPLOAD_DIR, uniqueName);
    
    // 复制文件
    fs.copyFileSync(sourcePath, destPath);
    
    return {
      originalName: imageName,
      fileName: uniqueName,
      filePath: destPath,
      url: `/uploads/${uniqueName}`
    };
  } catch (error) {
    log(`复制图片失败 [${imageName}]: ${error.message}`, 'error');
    throw error;
  }
}

// 获取文件信息
function getFileInfo(filePath) {
  try {
    const stats = fs.statSync(filePath);
    const mimeType = getMimeType(path.extname(filePath));
    
    return {
      size: stats.size,
      mimeType: mimeType
    };
  } catch (error) {
    log(`获取文件信息失败: ${error.message}`, 'error');
    return { size: 0, mimeType: 'image/jpeg' };
  }
}

// 根据扩展名获取MIME类型
function getMimeType(ext) {
  const mimeTypes = {
    '.jpg': 'image/jpeg',
    '.jpeg': 'image/jpeg', 
    '.png': 'image/png',
    '.bmp': 'image/bmp',
    '.gif': 'image/gif'
  };
  return mimeTypes[ext.toLowerCase()] || 'image/jpeg';
}

// 保存图片信息到数据库
async function saveImageToDB(imageInfo) {
  try {
    const newPhoto = new aiimg({
      img: imageInfo.url,
      name: `批量测试-${imageInfo.originalName}`,
      uploadTime: new Date(),
      originalName: imageInfo.originalName,
      fileSize: imageInfo.fileInfo.size,
      mimeType: imageInfo.fileInfo.mimeType
    });

    const savedPhoto = await newPhoto.save();
    log(`图片信息已保存到数据库: ${savedPhoto._id}`);
    return savedPhoto;
  } catch (error) {
    log(`保存图片信息失败: ${error.message}`, 'error');
    throw error;
  }
}

// 调用AI分析接口
async function analyzeImage(imagePath, imageId, imageName) {
  try {
    log(`开始AI分析: ${imageName}`, 'processing');
    
    // 创建FormData
    const formData = new FormData();
    formData.append('photo', fs.createReadStream(imagePath));
    formData.append('name', `AI分析-${imageName}`);
    
    // 调用分析接口
    const response = await axios.post(`${API_BASE_URL}/aiimg/analyzeFace`, formData, {
      headers: {
        ...formData.getHeaders(),
      },
      timeout: 30000, // 30秒超时
    });

    if (response.status === 200 && response.data.code === 200) {
      log(`AI分析成功: ${imageName}`, 'success');
      return response.data.data;
    } else {
      throw new Error(response.data.message || '分析失败');
    }
  } catch (error) {
    log(`AI分析失败 [${imageName}]: ${error.message}`, 'error');
    
    // 如果是网络错误，返回null让程序继续
    if (error.code === 'ECONNREFUSED' || error.code === 'ENOTFOUND') {
      log('AI服务可能未启动，跳过分析', 'warning');
      return null;
    }
    throw error;
  }
}

// 保存分析结果到数据库
async function saveAnalysisResult(imageId, analysisData) {
  try {
    if (!analysisData || !analysisData.analysis) {
      log('没有分析数据，跳过保存', 'warning');
      return null;
    }
    
    const analysis = analysisData.analysis;
    const faces = analysis.faces || [];
    
    // 如果没有检测到人脸，仍然保存基本信息
    if (faces.length === 0) {
      const saveData = new aisave({
        imageId: imageId,
        analysisTime: new Date(),
        faceCount: 0,
        aiAnalysis: analysis.aiAnalysis || '未检测到人脸',
        rawAnalysisData: analysisData
      });
      
      const saved = await saveData.save();
      log(`分析结果已保存(无人脸): ${saved._id}`);
      return saved;
    }
    
    // 取第一张人脸的数据进行保存
    const face = faces[0];
    
    const saveData = new aisave({
      imageId: imageId,
      analysisTime: new Date(),
      faceCount: analysis.faceCount || faces.length,
      
      // 性别信息
      gender: face.gender ? {
        gender: face.gender.gender,
        probability: face.gender.probability?.toString()
      } : undefined,
      
      // 年龄信息  
      age: face.age ? {
        age: face.age.age,
        ageRange: face.age.ageRange
      } : undefined,
      
      // 表情分析
      expressions: face.expressions ? {
        dominant: face.expressions.dominant,
        confidence: face.expressions.confidence?.toString(),
        scores: face.expressions.scores
      } : undefined,
      
      // 面部特征
      features: face.features ? {
        faceShape: face.features.faceShape,
        eyeDistance: face.features.eyeDistance,
        noseLength: face.features.noseLength,
        mouthWidth: face.features.mouthWidth,
        faceDimensions: face.features.faceDimensions
      } : undefined,
      
      // 黄金比例分析
      goldenRatio: face.goldenRatio,
      
      // 基础比例分析
      proportions: face.proportions,
      
      // 美容建议(转换为字符串)
      beautifyRecommendations: face.beautifyRecommendations ? 
        JSON.stringify(face.beautifyRecommendations) : undefined,
      
      // AI智能分析结果
      aiAnalysis: analysis.aiAnalysis,
      
      // 完整原始数据
      rawAnalysisData: analysisData
    });

    const saved = await saveData.save();
    log(`分析结果已保存: ${saved._id}`);
    return saved;
    
  } catch (error) {
    log(`保存分析结果失败: ${error.message}`, 'error');
    throw error;
  }
}

// 处理单个图片
async function processImage(imageName) {
  log(`开始处理: ${imageName}`, 'processing');
  
  try {
    // 1. 复制图片到上传目录
    const imageInfo = copyImageToUploadDir(imageName);
    imageInfo.fileInfo = getFileInfo(imageInfo.filePath);
    
    // 2. 保存图片信息到数据库
    const savedImage = await saveImageToDB(imageInfo);
    
    // 3. 调用AI分析
    const analysisResult = await analyzeImage(
      imageInfo.filePath, 
      savedImage._id, 
      imageName
    );
    
    // 4. 保存分析结果
    let analysisRecord = null;
    if (analysisResult) {
      analysisRecord = await saveAnalysisResult(savedImage._id, analysisResult);
    }
    
    log(`处理完成: ${imageName}`, 'success');
    stats.success++;
    
    return {
      success: true,
      imageName,
      imageId: savedImage._id,
      analysisId: analysisRecord?._id,
      faceCount: analysisResult?.analysis?.faceCount || 0
    };
    
  } catch (error) {
    log(`处理失败 [${imageName}]: ${error.message}`, 'error');
    stats.failed++;
    
    return {
      success: false,
      imageName,
      error: error.message
    };
  }
}

// 批量处理图片
async function processBatch(imageFiles, startIndex, batchSize) {
  const batch = imageFiles.slice(startIndex, startIndex + batchSize);
  const batchNum = Math.floor(startIndex / batchSize) + 1;
  const totalBatches = Math.ceil(imageFiles.length / batchSize);
  
  log(`开始处理第 ${batchNum}/${totalBatches} 批，包含 ${batch.length} 个图片`);
  
  const results = [];
  
  // 串行处理批次内的图片，避免并发冲突
  for (const imageName of batch) {
    const result = await processImage(imageName);
    results.push(result);
    
    // 图片间小延迟
    await new Promise(resolve => setTimeout(resolve, 500));
  }
  
  log(`第 ${batchNum} 批处理完成`);
  return results;
}

// 延迟函数
function delay(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

// 生成处理报告
function generateReport(allResults) {
  const duration = stats.endTime - stats.startTime;
  const minutes = Math.floor(duration / 60000);
  const seconds = Math.floor((duration % 60000) / 1000);
  
  console.log('\n' + '='.repeat(60));
  console.log('📊 批量处理完成报告');
  console.log('='.repeat(60));
  console.log(`⏱️  总耗时: ${minutes}分${seconds}秒`);
  console.log(`📁 总图片数: ${stats.total}`);
  console.log(`✅ 成功处理: ${stats.success}`);
  console.log(`❌ 处理失败: ${stats.failed}`);
  console.log(`⏭️  跳过图片: ${stats.skipped}`);
  console.log(`📈 成功率: ${((stats.success / stats.total) * 100).toFixed(1)}%`);
  
  // 成功处理的详情
  const successResults = allResults.flat().filter(r => r.success);
  if (successResults.length > 0) {
    console.log('\n✅ 成功处理的图片:');
    successResults.forEach((result, index) => {
      console.log(`${index + 1}. ${result.imageName} (人脸数: ${result.faceCount})`);
    });
  }
  
  // 失败处理的详情
  const failedResults = allResults.flat().filter(r => !r.success);
  if (failedResults.length > 0) {
    console.log('\n❌ 处理失败的图片:');
    failedResults.forEach((result, index) => {
      console.log(`${index + 1}. ${result.imageName}: ${result.error}`);
    });
  }
  
  console.log('\n' + '='.repeat(60));
}

// 主函数
async function main() {
  try {
    stats.startTime = Date.now();
    
    log('🚀 开始批量图片处理脚本');
    log(`📂 测试图片目录: ${TEST_IMAGES_DIR}`);
    log(`📁 上传目录: ${UPLOAD_DIR}`);
    log(`🌐 API地址: ${API_BASE_URL}`);
    log(`📦 批处理大小: ${BATCH_SIZE}`);
    
    // 获取所有图片文件
    const imageFiles = getImageFiles();
    if (imageFiles.length === 0) {
      log('没有找到图片文件，程序退出', 'warning');
      return;
    }
    
    stats.total = imageFiles.length;
    
    // 检查数据库连接
    try {
      await aiimg.findOne().limit(1);
      log('数据库连接正常', 'success');
    } catch (error) {
      log(`数据库连接失败: ${error.message}`, 'error');
      return;
    }
    
    // 检查AI服务是否可用
    try {
      const response = await axios.get(`${API_BASE_URL}/aiimg/status`, { timeout: 5000 });
      if (response.data.code === 200) {
        log(`AI服务状态: 模型已加载=${response.data.data.modelLoaded}`, 'success');
      }
    } catch (error) {
      log('AI服务检查失败，将尝试继续处理', 'warning');
    }
    
    log('开始批量处理...');
    
    // 分批处理
    const allResults = [];
    for (let i = 0; i < imageFiles.length; i += BATCH_SIZE) {
      const batchResults = await processBatch(imageFiles, i, BATCH_SIZE);
      allResults.push(batchResults);
      
      // 批次间延迟
      if (i + BATCH_SIZE < imageFiles.length) {
        log(`等待 ${DELAY_BETWEEN_BATCHES/1000} 秒后处理下一批...`);
        await delay(DELAY_BETWEEN_BATCHES);
      }
    }
    
    stats.endTime = Date.now();
    
    // 生成报告
    generateReport(allResults);
    
    log('🎉 所有图片处理完成！');
    
  } catch (error) {
    log(`程序执行出错: ${error.message}`, 'error');
    console.error(error);
  } finally {
    // 关闭数据库连接
    setTimeout(() => {
      process.exit(0);
    }, 2000);
  }
}

// 处理未捕获的异常
process.on('uncaughtException', (error) => {
  log(`未捕获异常: ${error.message}`, 'error');
  console.error(error);
  process.exit(1);
});

process.on('unhandledRejection', (reason, promise) => {
  log(`未处理的Promise拒绝: ${reason}`, 'error');
  console.error(reason);
  process.exit(1);
});

// 运行主函数
if (require.main === module) {
  main();
}

module.exports = {
  main,
  processImage,
  getImageFiles
};
